from contextlib import contextmanager


@contextmanager
def build_state():
    from core.documents import State
    state = State.objects().first()
    if state is None:
        state = State()
    state.is_building = True
    state.save()
    yield
    state.is_building = False
    state.save()


@contextmanager
def detect_state():
    from core.documents import MiddleState
    state = MiddleState.objects().first()
    if not state:
        state = MiddleState()
    state.isBuildModel = True
    state.save()
    yield
    state.isBuildModel = False
    state.save()